package com.lmabbe.common.rpc.filter;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.lmabbe.common.global.constant.GlobalConstant;
import com.lmabbe.common.global.context.LmabbeSessionUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * dubbo消费者拦截器
 *
 * @author lmabbe
 */
@Slf4j
@Activate(group = {CommonConstants.CONSUMER}, order = -30000)
public class ConsumerFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (invoker.getInterface().getPackage().getName().startsWith(GlobalConstant.SYSTEM.BASE_PACKAGE_NAME)) {
            log.error("ConsumerFilter=====>");
            HttpServletRequest request = getRequest();
            if (request != null) {
                RpcContext.getContext()
                        .setAttachment(GlobalConstant.SYSTEM.FROM_CLIENT, request.getHeader(GlobalConstant.SYSTEM.FROM_CLIENT))
                        .setAttachment(GlobalConstant.SYSTEM.TENANT_ID, request.getHeader(GlobalConstant.SYSTEM.TENANT_ID));
                String auth = request.getHeader(GlobalConstant.SYSTEM.AUTHORIZATION);
                if (StringUtils.isNotBlank(auth)) {
                    RpcContext.getContext().set(GlobalConstant.SYSTEM.AUTHORIZATION, auth.replace(GlobalConstant.SYSTEM.AUTHENTICATION_PREFIX, ""))
                            .setAttachment(GlobalConstant.SYSTEM.LOGIN_USER, JSONObject.toJSONString(SpringUtil.getBean(LmabbeSessionUser.class).loginUser()));
                }
            }
        }
        return invoker.invoke(invocation);
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes == null ? null : servletRequestAttributes.getRequest();
    }
}
